import { MIDEA_COMMON } from "@/config/constants";

declare let cordova: any;

/**
 * 使用cordova调用方法
 * @param name 名称
 * @param method 方法名称
 * @param params 参数
 * @returns promise
 */
// eslint-disable-next-line
function callApi(
  name: string,
  method: string,
  params: Array<any> | null
): Promise<any> {
  return new Promise((resolve, reject) => {
    if (typeof cordova !== "undefined") {
      try {
        // eslint-disable-next-line
        cordova.exec(
          (data: any) => {
            console.log("success", data);
            resolve(data);
          },
          (err: any) => {
            const error = err || "cordova执行" + method + "出错";
            console.log("error", error);
            reject(error);
          },
          name,
          method,
          params || []
        );
      } catch (e) {
        const error = e || "cordova存在，但执行方法报错";
        reject(error);
      }
    } else {
      resolve(null);
    }
    // } else if (process.env.CONFIG.env !== 'local' && process.env.CONFIG.env !== 'mock') {
    //   const error = new Error('cordova不存在')
    //   reject(error)
    // }
  });
}

/**
 * 退出模块
 * @returns Promise
 */
function exitModule(): Promise<any> | void {
  callApi(MIDEA_COMMON, "exit", []);
}

export { callApi, exitModule };
